//var uploadNum =$("#uploadedNum").html(); //已上传图片
var picDyna = "";
var SWFUploadUtils = {
    _$ : function(id){
        return document.getElementById(id);
    },
    insertPlaceholder : function(container,times){
        var that = this;
        if(typeof times === 'number'){
            for(var i = times; i > 0; i--){
                var placeholder = document.createElement("li");
                placeholder.className = "pic-upload-bd-upload-wait";
                that._$(container).appendChild(placeholder);
            }

        }
    },
    replacePlaceholder : function(container,index,elem){
        if(!isNaN(index)){
            var childs = this._$(container).getElementsByTagName("li");
            for(var i=0; i<childs.length; i++){
                if(childs[i].className === 'pic-upload-bd-upload-wait'){
                    var placeholder = childs[i];
                    this._$(container).replaceChild(elem,placeholder);
                    break;
                }
            }
        }
    },
    cancelPlaceholder : function(container){
        var childs = this._$(container).getElementsByTagName("li");
        for(var i = childs.length-1; i>=0; i--){
            if(childs[i].className === 'pic-upload-bd-upload-wait'){
                childs[i].parentNode.removeChild(childs[i]);
            }
        }
    }
};

function preLoad() {
    if (!this.support.loading) {
        dynatool.isSupportFlash=false;
        return false;
    }
    return true;
}
function loadFailed() {
    dynatool.isSupportFlash=false;
    if(console)console.log('flash加载失败');
    //alertErrorTip("flash加载失败",true);
}
function tooltip(_content){
    alertErrorTip("不支持该格式",false);
}
function fileQueueError(file, errorCode, message) {
    try {
        var imageName = "error.gif";
        var errorName = "";
        if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
            errorName = "You have attempted to queue too many files.";
        }

        if (errorName !== "") {
            alertErrorTip(errorName,false);
            return;
        }

        switch (errorCode) {
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                //imageName = "zerobyte.gif";
                break;
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                //imageName = "toobig.gif";
                alertErrorTip("部分图片超过10M，请调整大小后再上传",false);
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                alertErrorTip("不支持此格式文件",false);
                break;
            default:
                alertErrorTip("系统错误，请联系管理员",false);
                break;
        }

    //addImage("images/" + imageName);

    } catch (ex) {
        this.debug(ex);
    }

}

/**
 *	选择图片的对话框消失以后操作
 **/
function fileDialogComplete(numFilesSelected, numFilesQueued, totalFilesQueued) {
    var maxNum = parseInt($("#canUploadNum").html()); //还能上传多少张图片
    var uploadedNum = parseInt($("#uploadedNum").html()); //已经上传多少张图片
    if(numFilesQueued>maxNum){
        if(maxNum == 0) {
            alertErrorTip("本次上传总图片数量不能超过"+uploadedNum+"张",false);
        } else {
            alertErrorTip("本次上传图片数量不能超过"+maxNum+"张",false);
        }
        swfu.cancelQueue();
        return;
    }

    
    /** 插入占位符 */
    SWFUploadUtils.insertPlaceholder("divFileProgressContainer",numFilesQueued);
	
    try {
        if (numFilesQueued > 0) {
            this.startResizedUpload(this.getFile(0).ID, this.customSettings.resizedImgWidth,
                this.customSettings.resizedImgHeight, SWFUpload.RESIZE_ENCODING.JPEG, this.customSettings.resizedImgQuality,
                false,this.customSettings.resizedImgCondition);
        }
    } catch (ex) {
        alertErrorTip(ex,false);
        this.debug(ex);
    }
	
}




/**
 *	更新进度条
 */
function uploadProgress(file, bytesLoaded) {
    try {
        var percent = Math.ceil((bytesLoaded / file.size) * 100)<=100? Math.ceil((bytesLoaded / file.size) * 100):100;
        if (file.uploadtype === SWFUpload.UPLOAD_TYPE.RESIZED) {
            percent = 30;
        }
        var progress = new FileProgress(file,  this.customSettings.upload_target);
        progress.setProgress(percent);
    } catch (ex) {
        this.debug(ex);
    }
}

/**
 * 更新一张图片成功
 */
function uploadSuccess(file, serverData) {
    try {
        var progress = new FileProgress(file,  this.customSettings.upload_target);
        var data = eval('(' + serverData + ')');
        switch (data.retCode) {
            case 0:
                //只处理1024x1024规格的。
                progress.setComplete(file, data);
                uploadListen(1);
                //更新上传数量
                /*                maxNum = maxNum - 1;
                uploadNum = uploadNum+1;
                $("#uploadedNum").html(uploadNum);
                $("#canUploadNum").html(maxNum);*/

                break;
            case 5:
            case 14:
                alertErrorTip('部分图片超过10M，请调整大小后再上传',false);
                progress.setCancelled();
                break;
            case 6:
                alertErrorTip('处理图片的时候发生错误,请找管理员帮忙',false);
                progress.setCancelled();
                break;
            case 12:
                alertErrorTip('未登录或超时,请先登录',false);
                progress.setCancelled();
                swfu.cancelQueue();
                break;
            case 21:
                alertErrorTip('不支持此格式文件',false);
                progress.setCancelled();
                break;
            default :
                alertErrorTip('系统出错<br />错误码：' + data.retCode,false);
                progress.setCancelled();
                break;

        }
		
    } catch (ex) {
        this.debug(ex);
    }
}

/**
 * 整个上传成功
 */
function uploadComplete(file) {
    try {
        /*  I want the next upload to continue automatically so I'll call startUpload here */
        if (this.getStats().files_queued > 0) {
            var progress = new FileProgress({
                id:"tmp_fpID"
            },  this.customSettings.upload_target);
            progress.setProgress(0);
            this.startResizedUpload(this.getFile(0).ID, this.customSettings.resizedImgWidth,
                this.customSettings.resizedImgHeight, SWFUpload.RESIZE_ENCODING.JPEG, this.customSettings.resizedImgQuality,
                false,this.customSettings.resizedImgCondition);

        } else {
            $("#progressWrap").hide();
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadError(file, errorCode, message) {
	
    var imageName =  "error.gif";
    var progress;
    try {
        switch (errorCode) {
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                try {
                    progress = new FileProgress(file,  this.customSettings.upload_target);
                    progress.setCancelled();

                }
                catch (ex1) {
                    this.debug(ex1);
                }
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                try {
                    progress = new FileProgress(file,  this.customSettings.upload_target);
                    progress.setCancelled();
                }
                catch (ex2) {
                    this.debug(ex2);
                }
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                alertErrorTip("部分图片超过10M，请调整大小后再上传",false);
                break;
            case SWFUpload.UPLOAD_ERROR.RESIZE:
                alertErrorTip("可能是你的图片尺寸过大，请调整后再上传",false);
                break;
            default:
                alertErrorTip("系统错误，请联系管理员",false);
                break;
        }

    //addImage("images/" + imageName);

    } catch (ex3) {
        this.debug(ex3);
    }

}


FileProgress.prototype.setStatus = function (status) {
    // this.fileProgressElement.childNodes[2].innerHTML = status;
    };



/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */
/**
 * 进度条初始化和显示图片效果
 *
 */
function FileProgress(file, targetID) {
    this.fileProgressID = file.id;
    if (document.getElementById("tmp_fpID")) {
        document.getElementById("tmp_fpID").id = this.fileProgressID;
    }
    this.fileProgressWrapper = document.getElementById(this.fileProgressID);
    if (!this.fileProgressWrapper) {
        this.fileProgressWrapper = document.createElement("li");
        this.fileProgressWrapper.className = "pic-upload-bd-upload-loading";
        this.fileProgressWrapper.id = this.fileProgressID;
        
        //<img>
        var fileProgressIMG = document.createElement("img");
        fileProgressIMG.src = "http://www1.pcauto.com.cn/2014/club/v4_1/common/loading.gif";

        //<i>
        var fileProgressI = document.createElement("i");
        fileProgressI.appendChild(document.createTextNode("已上传0%"));
        
        //<em>
        var fileProgressEM = document.createElement("em");
        //<b>
        var fileProgressB = document.createElement("b");
        fileProgressB.style.width = 0;
        fileProgressEM.appendChild(fileProgressB);

        this.fileProgressWrapper.appendChild(fileProgressIMG);
        this.fileProgressWrapper.appendChild(fileProgressI);
        this.fileProgressWrapper.appendChild(fileProgressEM);

        /** 替换占位符 */
        SWFUploadUtils.replacePlaceholder(targetID, file.index, this.fileProgressWrapper);
    }

    this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
    this.fileProgressWrapper.childNodes[1].innerHTML = "已上传" + percentage + "%";
    this.fileProgressWrapper.childNodes[2].childNodes[0].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function (file,imgobjs) {
    var nodeParent = this.fileProgressWrapper;
    nodeParent.className = "";
    var imgText ='<img width="120" height="80" alt="" src="'+imgobjs.files[0].url+'" /><a href="javascript:void(0)" onclick="deletePic(this)" class="pic-delete" title="删除这张相片"></a>';
    nodeParent.innerHTML = imgText;
    //$("#spanButtonPlaceholder").attr("style","display:none");
    if (typeof fileCallback == "function") {
        fileCallback(imgobjs);
    }
  
    
};
FileProgress.prototype.setError = function () {

    };
FileProgress.prototype.setCancelled = function () {
    var nodeParent = this.fileProgressWrapper;
    nodeParent.parentNode.removeChild(nodeParent);
};



